package com.liaoyin.travel.service.task;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.task.TaskExceptionDescriptionMapper;
import com.liaoyin.travel.entity.UserTeam;
import com.liaoyin.travel.entity.task.TaskExceptionDescription;
import com.liaoyin.travel.entity.task.TaskReceivingRecords;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.RongUtils;
import com.liaoyin.travel.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;


/**
 * @项目名：旅投
 * @作者：lijing
 * @描述：任务异常说明
 * @日期：Created in 2018/6/20 14:55
 */
@Service
public class TaskExceptionDescriptionService extends BaseService<TaskExceptionDescriptionMapper, TaskExceptionDescription> {

	@Autowired
	private TaskService taskService;	
	@Autowired
    private TaskReceivingRecordsService taskReceivingRecordsService;
	@Autowired
    private TaskExceptionDescriptionService taskExceptionDescriptionService;

	
	
	/****
	 * 
	     * @方法名：insertOrUpdateTaskExceptionDescription
	     * @描述： 新增或修改任务异常说明
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	@Transactional(rollbackFor = Exception.class)
	public int insertOrUpdateTaskExceptionDescription(TaskExceptionDescription taskExceptionDescription) {
		int result = 0;
		taskExceptionDescription.setIsDelete((short)0);
		if(taskExceptionDescription.getId() !=null && !"".equals(taskExceptionDescription.getId())) {

			result = this.mapper.updateByPrimaryKeySelective(taskExceptionDescription);
		}else {
			taskExceptionDescription.setCreatTime(new Date());
			taskExceptionDescription.setId(UUIDUtil.getUUID());
			result = this.mapper.insertSelective(taskExceptionDescription);
		}
		return result;
	}

	/**
	　* @description: TODO  查询异常任务的列表
	　* @param [num, size, exceptionType]
	　* @return java.util.List<com.liaoyin.travel.entity.task.TaskExceptionDescription>
	　* @throws
	　* @author privatePanda777@163.com
	　* @date 2019/8/7 16:01
	　*/
	public List<TaskExceptionDescription> selectExceptionTaskList(Integer num,Integer size,Integer exceptionType,String qurtyType){

		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		/** 景区id */
		String scenicId = user.getScenicId();

		String teamId = "";
		if(qurtyType != null && "1".equals(qurtyType)) {
			if(user.getAssumeOffice()!=null && user.getAssumeOffice().intValue() == 1) {
				List<UserTeam> teamList = user.getUserTeamList();
				if(teamList!=null && teamList.size() >0) {
					StringBuffer str = new StringBuffer();
					for(UserTeam u :teamList) {
						str.append(u.getTeamId()+",");
					}
					if(str !=null) {
						teamId=str.toString().substring(0,str.toString().lastIndexOf(","));
						str = null;
					}
				}
				
			}
			
		}
		PageHelper.startPage(num,size);
		System.err.println("exceptionType="+exceptionType);
		System.err.println("teamId="+teamId);
		System.err.println("scenicId="+scenicId);
		List<TaskExceptionDescription> list = this.mapper.selectExceptionTaskList(exceptionType,teamId,scenicId);
		list.forEach(taskExceptionDescription -> {
			System.err.println("任务审核 : " + taskExceptionDescription);
		});

		return list;
	}

	/**
	 * @方法名：selectNewExceptionTaskList
	 * @描述： 管理端查询自己的发布的异常任务列表
	 * @作者： kjz
	 * @日期： Created in 2020/4/14 20:00
	 */
	public PageInfo<TaskExceptionDescription> selectNewExceptionTaskList(Integer num, Integer size, Integer exceptionType, String qurtyType, String taskName) {

		UserInfo currentUser = PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(currentUser).orElseThrow(() -> new BusinessException("not.login"));

		/** 景区id */
		String scenicId = currentUser.getScenicId();
		String userId = null;

		//如果是移动端查询
		if(qurtyType != null && "1".equals(qurtyType)){
			userId = currentUser.getId();
		}

		System.err.println("qurtyType="+qurtyType);
		System.err.println("exceptionType="+exceptionType);
		System.err.println("userId="+userId);
		System.err.println("scenicId="+scenicId);
		System.err.println("taskName="+taskName);

		PageHelper.startPage(num,size);
		List<TaskExceptionDescription> list = this.mapper.selectNewExceptionTaskList(exceptionType,userId,scenicId,taskName);
		System.err.println("数据量="+list.size());

		System.err.println("==============================================================");


		PageInfo<TaskExceptionDescription> pageInfo = new PageInfo<>(list);
		System.err.println("pageInfo="+pageInfo);
		return pageInfo;
	}

	/**
	　* @description: TODO  查询异常任务详情
	　* @param [id]
	　* @return com.liaoyin.travel.entity.task.TaskExceptionDescription
	　* @throws
	　* @author privatePanda777@163.com
	　* @date 2019/8/8 10:57
	　*/
	public TaskExceptionDescription selectExceptionTaskById(String id){
		TaskExceptionDescription taskExceptionDescription = this.mapper.selectByPrimaryKey(id);
		String task_id = taskExceptionDescription.getTaskId();
		taskExceptionDescription.setTaskName(taskService.selectById(task_id).getTaskName());
		return taskExceptionDescription;
	}
	
	
	/***8
	 * 
	     * @方法名：updateExceptionTask
	     * @描述： 更新异常任务状态
	     * @作者： lijing
	     * @日期： 2019年8月24日
	 */
	@Transactional(rollbackFor = Exception.class)
	public void  updateExceptionTask(String exceptionId,Integer exceptionStatus,String exeptionContext,String taskId,String userId) {
		
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		TaskExceptionDescription taskExceptionDescription = new TaskExceptionDescription();
        taskExceptionDescription.setId(exceptionId);
        taskExceptionDescription.setHandlerUserId(user.getId());
        taskExceptionDescription.setHandlerContext(exeptionContext);
        if (null != exceptionStatus){
            taskExceptionDescription.setHandlerStatus(exceptionStatus.shortValue());
        }
        TaskReceivingRecords records = new TaskReceivingRecords();
		System.err.println("taskId = " + taskId);
        records.setTaskId(taskId);
        records.setUserId(userId);
        if (null != exceptionStatus && exceptionStatus == 1){
            List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(taskId, null, "1,2,4,");
            if(taskReceivingRecords!=null && taskReceivingRecords.size() >0) {
            	for (TaskReceivingRecords record : taskReceivingRecords) {
                    record.setTastStatus((short)3);
                    record.setTaskEndTime(new Date());
                    this.taskReceivingRecordsService.updateTaskReceivingRecords(record);
                    if (null != userId && record.getUserId() != userId){
                        //推送任务给指派人
                        HashMap<String, String> map = new HashMap<>();
                        map.put("fromUserId", "System");
                        map.put("toUserId",record.getUserId());
                        map.put("objectName","RC:TxtMsg");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("content", "当前任务已撤销！请执行其他任务！");
                        jsonObject.put("extra", "当前任务已撤销！请执行其他任务！" );
                        map.put("content",jsonObject.toJSONString());
                        map.put("pushContent","当前任务已撤销！请执行其他任务！");
                        try {
                            String s = RongUtils.groupManagement(map, "7");
                            System.out.println(s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
                taskExceptionDescription.setTastStatus((short)3);
            }
        } else if (null != exceptionStatus && exceptionStatus == 2){
            List<TaskReceivingRecords> receivingRecords = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(taskId, null, null);
            if(receivingRecords!=null && receivingRecords.size() >0) {
            for (TaskReceivingRecords record : receivingRecords) {
                record.setTastStatus((short)2);
                this.taskReceivingRecordsService.updateTaskReceivingRecords(record);
                if (null != userId && record.getUserId() != userId){
                    //推送任务给指派人
                    HashMap<String, String> map = new HashMap<>();
                    map.put("fromUserId", "System");
                    map.put("toUserId",record.getUserId());
                    map.put("objectName","RC:TxtMsg");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("content", "撤销未通过请继续执行任务！");
                    jsonObject.put("extra", "撤销未通过请继续执行任务！" );
                    map.put("content",jsonObject.toJSONString());
                    map.put("pushContent","撤销未通过请继续执行任务！");
                    try {
                        String s = RongUtils.groupManagement(map, "7");
                        System.out.println(s);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            taskExceptionDescription.setTastStatus((short)2);
        }
       }
        this.taskExceptionDescriptionService.insertOrUpdateTaskExceptionDescription(taskExceptionDescription);
	}

	/**
	　* @description: TODO  删除异常任务
	　* @param [ids]
	　* @return int
	　* @throws
	　* @author privatePanda777@163.com
	　* @date 2019/9/25 上午9:59
	　*/
	public int deleteTaskExceptionDescription(String ids){
		int i = 0;
		String[] split = ids.split(",");
		if (split.length > 0){
            i = this.mapper.deleteTaskExceptionDescription(split);
        }
		return i;
	}


}
